import { each, get } from 'lodash';
import getPinyin from '../../../utils/getPy';
import CellType from '../celltypes';
import { Button } from 'antd';
import { toJS } from 'mobx';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

function combindCellType(cellType, fieldType) {
    const [type] = fieldType;
    if (type == 'select') {
        cellType.fieldType = ['select', 'select', cellType.fieldType[2], cellType.fieldType[3]];
    } else {
        cellType.fieldType = fieldType;
    }
    if (fieldType === void 0) {
        return undefined;
    }
    return cellType;
}
export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        try {
            const { sheet, sheetIndex, sheetName, selections,
                fieldType, openSelectOptionsDialog, getFieldIndex, getMainTableFieldName, getFieldName, getSelectOptionsDatas
                , getSelectedRelatedChild, refreshSelectCelltypes, doCheck } = options;
            sheet.suspendPaint();
            if (isUndo) {
                const {
                    _oldFieldType,
                    _oldCellTypes,
                    _oldTextIndent,
                    _oldBackgroundImageLayout,
                    _oldBackgroundImage,
                    _oldBindingPath
                } = options;
                each(_oldFieldType, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    const cellType = cell.cellType();
                    cellType.fieldType = v;
                    cell.cellType(cellType);
                });

                each(_oldCellTypes, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.cellType(v);
                });
                each(_oldTextIndent, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.textIndent(v);
                });
                each(_oldBackgroundImageLayout, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.backgroundImageLayout(v);
                });
                each(_oldBackgroundImage, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.backgroundImage(v);
                });
                each(_oldBindingPath, (v, key) => {
                    const [row, col] = key.split(',');
                    const cell = sheet.getCell(parseInt(row), parseInt(col));
                    cell.bindingPath(v);
                });
            } else {
                options._oldFieldType = {};
                options._oldCellTypes = {};
                options._oldTextIndent = {};
                options._oldBackgroundImageLayout = {};
                options._oldBackgroundImage = {};
                options._oldBindingPath = {};
                const cellTypes = [];
                const FieldCellType = CellType('FieldCellType');
                selections.forEach(selection => {
                    const { row, col, rowCount, colCount } = selection;
                    for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
                        for (let colIndex = 0; colIndex < colCount; colIndex++) {
                            const currentRow = row + rowIndex;
                            const currentCol = col + colIndex;
                            const currentKey = `${currentRow},${currentCol}`;
                            const span = sheet.getSpan(currentRow, currentCol);
                            let currentCell;
                            if (span) {
                                if (span.row !== currentRow || span.col !== currentCol) {
                                    continue;
                                }
                                currentCell = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
                            } else {
                                currentCell = sheet.getCell(currentRow, currentCol);
                            }
                            let currentSingleCell;
                            const table = sheet.tables.find(currentCell.row, currentCell.col);
                            if (table) {
                                currentSingleCell = sheet.getCell(table.dataRange().row, currentCell.col);
                            } else {
                                currentSingleCell = sheet.getCell(currentCell.row, currentCell.col);
                            }
                            let cellType = currentSingleCell.cellType();
                            if (cellType && cellType.typeName === 'FieldCellType') {
                                options._oldFieldType[currentKey] = cellType.fieldType;
                                options._oldBackgroundImage[currentKey] = currentSingleCell.backgroundImage();

                                cellType = combindCellType(cellType, fieldType);
                                currentSingleCell
                                    .cellType(cellType)
                                    .textIndent(2.5)
                                    .backgroundImage(cellType.getFieldTypeImage())
                                    .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none);
                            } else {
                                const mainTable = `mainTable_${sheetIndex}`;
                                const fieldIndex = getFieldIndex(mainTable, "mainTable");
                                const label = getMainTableFieldName(sheet, currentCell.row, currentCell.col, fieldIndex);
                                const fieldName = getFieldName(mainTable, "mainTable", getPinyin(label)[0]);
                                cellType = new FieldCellType();
                                cellType.fieldName = fieldName;
                                cellType.label = label;
                                cellType.fieldIndex = fieldIndex;
                                cellType.fieldType = fieldType;
                                options._oldCellTypes[currentKey] = currentSingleCell.cellType();
                                options._oldBackgroundImage[currentKey] = currentSingleCell.backgroundImage();
                                options._oldBackgroundImageLayout[currentKey] = currentSingleCell.backgroundImageLayout();
                                options._oldBindingPath[currentKey] = currentSingleCell.bindingPath();
                                options._oldTextIndent[currentKey] = currentSingleCell.textIndent();

                                currentSingleCell.textIndent(2.5)
                                    .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                                    .backgroundImage(cellType.getFieldTypeImage())
                                    .cellType(cellType)
                                    .bindingPath(`${sheetName}.${fieldName}`);
                            }
                            cellTypes.push(cellType);
                        }
                    }
                });
                const [value] = fieldType || [];
                if (value === 'select') {
                    const save = () => {
                        const checkRes = doCheck();
                        if(!checkRes) {
                            return;
                        }
                        cellTypes.forEach(cellType => {
                            cellType.fieldType[2] = { datas: toJS(getSelectOptionsDatas()), relatedChild: getSelectedRelatedChild() };
                            // 此处要将新增的下拉框增加到store中去
                            // 下拉选择保存后，由于不确定改动哪些，只能全局清空，后期可改为遍历下更改项，保持同步
                            if (cellType.autoFillin) {
                                cellType.autoFillin = false;
                                cellType.fieldType[3] = [];
                            }
                        })
                        openSelectOptionsDialog(undefined, undefined, undefined, false);

                        refreshSelectCelltypes();
                    }
                    openSelectOptionsDialog(
                        cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].datas') || [],
                        cellTypes.length > 1 ? [] : get(cellTypes, '[0].fieldType[2].relatedChild') || '',
                        <Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}</Button>,
                        true
                    );

                } else {
                    refreshSelectCelltypes();
                }
            }
            sheet.resumePaint();
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
    }
};